package com.lsl.musicplayer;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lsl.musicplayer.adapter.MusicListAdapter;
import com.lsl.musicplayer.broadcast.MusicBroadcast;
import com.lsl.musicplayer.service.MusicService;
import com.lsl.musicplayer.util.AudioScanner;
import com.lsl.musicplayer.util.FilePathUtil;
import com.lsl.musicplayer.util.FormatTime;
import com.lsl.musicplayer.util.GetFileName;
import com.lsl.musicplayer.util.ToastUtil;
import com.lsl.musicplayer.view.VisualizerView;

import java.util.ArrayList;
import java.util.List;

/**
 * author lishilin
 * date 2023/8/8
 * desc 音乐activity类，负责扫描音频、进度显示、控制UI和加载recycleView等
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageButton preSong;
    private ImageButton playOrPause;
    private ImageButton nextSong;
    private SeekBar musicSeekbar;
    private TextView currentProcess;
    private TextView maxProcess;
    private TextView openMusic;
    private FormatTime formatTime;
    private TextView musicTitle;
    private ImageButton songList;
    private GetFileName getFileName;
    private List<String> musicList;
    private int currentMusicIndex;
    RecyclerView recyclerView;
    private VisualizerView mVisualizer;
    private MusicListAdapter musicListAdapter;
    private RecyclerView.OnItemTouchListener mItemClickListener;
    private static final int MUSIC_REQUEST_CODE = 110;
    Dialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        registerMyBroadcast();
        // 允许屏幕自动旋转
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        scanMusic();
        ToastUtil.showLongToast(this, "自动扫描音频");
        //onReplayPlayMusic();
    }

    private void initView() {
        preSong = (ImageButton) findViewById(R.id.pre_song);
        playOrPause = (ImageButton) findViewById(R.id.play_or_stop);
        nextSong = (ImageButton) findViewById(R.id.next_song);
        musicSeekbar = (SeekBar) findViewById(R.id.music_seekBar);
        currentProcess = (TextView) findViewById(R.id.current_process);
        maxProcess = (TextView) findViewById(R.id.max_process);
        openMusic = (TextView) findViewById(R.id.open_music);
        musicTitle = (TextView) findViewById(R.id.musicTitle);
        songList = (ImageButton) findViewById(R.id.songList);
        mVisualizer = findViewById(R.id.mVisualizerView);
        songList.setOnClickListener(this);
        openMusic.setOnClickListener(this);
        preSong.setOnClickListener(this);
        nextSong.setOnClickListener(this);
        playOrPause.setOnClickListener(this);
        formatTime = new FormatTime();
        getFileName = new GetFileName();
        currentMusicIndex = 0;
        musicList = new ArrayList<>();
        updateSeekbar();
        dialog = new Dialog(MainActivity.this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pre_song:
                if (musicList.size() <= 1) {
                    ToastUtil.showShortToast(this,"当前只有一首歌曲！");
                    return;
                }
                if (currentMusicIndex <= 0) {
                    currentMusicIndex = musicList.size() - 1;
                    changeMusic(currentMusicIndex);
                } else {
                    currentMusicIndex--;
                    changeMusic(currentMusicIndex);
                }
                break;
            case R.id.next_song:
                if (musicList.size() <= 1) {
                    ToastUtil.showShortToast(this,"当前只有一首歌曲！");
                    return;
                }
                if (currentMusicIndex >= musicList.size() - 1) {
                    currentMusicIndex = 0;
                    changeMusic(currentMusicIndex);
                } else {
                    currentMusicIndex++;
                    changeMusic(currentMusicIndex);
                }
                break;
            case R.id.play_or_stop:
                playMusic(currentMusicIndex);
                break;
            case R.id.open_music:
                toOpenMusic();
                break;
            case R.id.songList:
                showCustomDialog();
        }
    }
    //不好用，暂时弃用
    private void onReplayPlayMusic() {
        if (musicList != null) {
            playMusic(currentMusicIndex);
        }
    }

    private void scanMusic() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            // 已经获得权限，执行相关操作
            AudioScanner audioScanner = new AudioScanner();
            List<String> scanFiles = audioScanner.scanAudioFiles(this);
            for (String file : scanFiles
            ) {
                musicList.add(getFileName.getFileName(file));
            }
            Intent intent = new Intent(this, MusicService.class);
            intent.setAction("INIT_MUSIC_LIST");
            intent.putExtra("musicList", (ArrayList<String>) scanFiles);
            startService(intent);
        } else {
            // 没有获得权限，需要进行运行时权限请求
            Log.i("权限", "没有权限！");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 120);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 120) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限，执行相关操作
                Log.i("权限", "同意");
                AudioScanner audioScanner = new AudioScanner();
                List<String> scanFiles = audioScanner.scanAudioFiles(this);
                for (String file : scanFiles
                ) {
                    musicList.add(getFileName.getFileName(file));
                }
                Intent intent = new Intent(this, MusicService.class);
                intent.setAction("INIT_MUSIC_LIST");
                intent.putExtra("musicList", (ArrayList<String>) scanFiles);
                startService(intent);
            } else {
                Toast.makeText(this, "你已拒绝相关权限", Toast.LENGTH_SHORT);
            }
        }
    }

    /**
     * 处理服务发送的广播
     */
    MusicBroadcast musicBroadcast = new MusicBroadcast() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //处理UI
            switch (intent.getAction()) {
                case "TOTAL_PROCESS":
                    int maxPro = intent.getIntExtra("max", 0);
                    maxProcess.setText(formatTime.SecondToSongTime(maxPro / 1000));
                    musicSeekbar.setMax(maxPro);
                    break;
                case "MUSIC_PLAY":
                    playOrPause.setImageResource(R.drawable.pause);
                    //启动音符跳动
                    mVisualizer.setIsPlay(true);
                    mVisualizer.updateDraw();
                    break;
                case "MUSIC_PAUSE":
                    playOrPause.setImageResource(R.drawable.play);
                    mVisualizer.setIsPlay(false);
                    break;
                case "UPDATE_PROCESS":
                    int currentProcess = intent.getIntExtra("process", 0);
                    updateProcess(currentProcess);
                    break;
            }
        }
    };

    /**
     * 注册广播
     */
    public void registerMyBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("TOTAL_PROCESS");
        intentFilter.addAction("MUSIC_PLAY");
        intentFilter.addAction("MUSIC_PAUSE");
        intentFilter.addAction("UPDATE_PROCESS");
        registerReceiver(musicBroadcast, intentFilter);
    }

    /**
     * 更新进度条
     *
     * @param currentProcess
     */
    private void updateProcess(int currentProcess) {
        musicSeekbar.setProgress(currentProcess);
        this.currentProcess.setText(formatTime.SecondToSongTime(currentProcess / 1000));
    }

    private void playMusic(int index) {
        Intent intent = new Intent(this, MusicService.class);
        intent.setAction("ACTION_PLAY");
        intent.putExtra("index", index);
        startService(intent);
    }

    /**
     * 切换音乐
     *
     * @param index
     */
    private void changeMusic(int index) {
        Intent intent = new Intent(this, MusicService.class);
        intent.setAction("CHANGE_MUSIC");
        intent.putExtra("changeIndex", index);
        startService(intent);
        //修改标题
        musicTitle.setText(musicList.get(index));
        currentMusicIndex = index;

    }

    /**
     * 打开文件寻找音乐
     */
    private void toOpenMusic() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, MUSIC_REQUEST_CODE);
    }

    //处理选择音频后的回调
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED || data == null) {
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
        Uri uri = data.getData();
        String filePath = FilePathUtil.uriToFileApiQ(this, uri);
        System.out.println("传统文件路径：" + filePath);
        String title = getFileName.getFileName(filePath);
        musicList.add(title);
        musicTitle.setText(title);
        Intent intent = new Intent(this, MusicService.class);
        intent.setAction("ACTION_SET_PATH");
        int playIndex = musicList.size() - 1;
        currentMusicIndex = playIndex;
        intent.putExtra("musicPath", filePath);
        intent.putExtra("playIndex", playIndex);
        startService(intent);
    }


    /**
     * 更新进度条
     */
    private void updateSeekbar() {
        musicSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int currentTime = seekBar.getProgress();
                currentProcess.setText(formatTime.SecondToSongTime(currentTime / 1000));
                Intent intent = new Intent(MainActivity.this, MusicService.class);
                intent.setAction("CHANGE_PROCESS");
                intent.putExtra("process", currentTime);
                startService(intent);
            }
        });
    }

//    /**
//     * 初始化recycleView数据，绑定适配器
//     */
//    private void initListView() {
//        recyclerView = findViewById(R.id.recyclerView);
//        recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 设置布局管理器，可选其他布局管理器，如GridLayoutManager
//        musicListAdapter = new MusicListAdapter(musicList);
//        recyclerView.setAdapter(musicListAdapter); // 设置适配器，data为数据列表
//        mItemClickListener = new MyRecyclerViewClickListener();
//        recyclerView.addOnItemTouchListener(mItemClickListener);
//    }

    /**
     * 显示播放列表弹窗,显示recycleView的数据
     */
    private void showCustomDialog() {
        if (dialog == null) {
            return;
        }
        dialog.setContentView(R.layout.custom_dialog);
        RecyclerView recyclerView = dialog.findViewById(R.id.recycler_view_dialog);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        musicListAdapter = new MusicListAdapter(musicList);
        recyclerView.setAdapter(musicListAdapter); // 设置适配器，data为数据列表
        mItemClickListener = new MyRecyclerViewClickListener();
        recyclerView.addOnItemTouchListener(mItemClickListener);
        dialog.show();

        ImageButton close = dialog.findViewById(R.id.musicListClose);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
    }

    /**
     * recycleView触摸事件
     */
    public class MyRecyclerViewClickListener extends RecyclerView.SimpleOnItemTouchListener {

        @Override
        public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
            // 处理点击事件的逻辑
            View childView = rv.findChildViewUnder(e.getX(), e.getY());
            if (childView != null && mItemClickListener != null && rv.getLayoutManager() != null) {
                int position = rv.getChildAdapterPosition(childView);
                if (position != RecyclerView.NO_POSITION) {
                    // 处理点击事件的逻辑
                    Log.d("执行列表点击事件：", "一次");
                    changeMusic(position);
                    dialog.cancel();
                }
            }
            return true;//拦截点击之后的后续事件
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}